<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌编号" prop="brandId">
        <el-select v-model="queryParams.brandId" filterable placeholder="请选择品牌编号" clearable size="small">
          <el-option
            v-for="brand in brandList"
            :label="brand.brandName"
            :value="brand.brandId" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型编号" prop="typeId">
        <el-select v-model="queryParams.typeId" filterable placeholder="请选择类型编号" clearable size="small">
          <el-option
            v-for="type in goodsTypeList"
            :label="type.typeName"
            :value="type.typeId" />
        </el-select>
      </el-form-item>
      <el-form-item label="系列编号" prop="seriesId">
        <el-select v-model="queryParams.seriesId" filterable placeholder="请选择系列编号" clearable size="small">
          <el-option
            v-for="series in seriesList"
            :label="series.seriesName"
            :value="series.seriesId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['share:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['share:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['share:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['share:goods:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddList"
          v-hasPermi="['share:goods:add']"
        >批量新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="goodsId" />
      <el-table-column label="商品名称" align="center" prop="goodsName">
        <template slot-scope="scope">
          <router-link :to="'/goods/price/' + scope.row.goodsId" class="link-type">
            <span>{{ scope.row.goodsName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="品牌编号" align="center" prop="brandId" :formatter="brandFormatter" />
      <el-table-column label="类型编号" align="center" prop="typeId" :formatter="typeFormatter" />
      <el-table-column label="系列编号" align="center" prop="seriesId" :formatter="seriesFormatter" />
<!--      <el-table-column label="规格组" align="center" prop="specsMap" :formatter="specsFormatter" :show-overflow-tooltip="true" />-->
      <el-table-column label="成色组" align="center" prop="qualityIds" :formatter="qualityFormatter" :show-overflow-tooltip="true" />
      <el-table-column label="是否显示" align="center" prop="hasShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.hasShow"
            @change="hasShowChange(scope.row)"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="goodsSort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['share:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['share:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="批量新增" :visible.sync="addOpen" width="80%" append-to-body>
      <el-form ref="addForm" :model="addFrom" label-width="80rpx">
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌编号" prop="brandId">
              <el-select v-model="addFrom.brandId" filterable placeholder="请选择品牌编号" @change="brandIdChange">
                <el-option
                  v-for="brand in brandList"
                  :label="brand.brandName"
                  :value="brand.brandId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型编号" prop="typeId">
              <el-select v-model="addFrom.typeId" placeholder="请选择类型编号">
                <el-option
                  v-for="type in goodsTypeOptions"
                  :label="type.typeName"
                  :value="type.typeId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="padding: 10px"><input type="file" accept=".xlsx, .xls" @change="changeFile" /></div>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="confirmAddList"
        v-hasPermi="['share:goods:add']"
      >确认添加</el-button>
      <el-table v-loading="loading" :data="addList">
        <el-table-column label="商品名称" align="center" prop="goodsName" />
        <el-table-column label="品牌编号" align="center" prop="brandId" :formatter="brandFormatter" />
        <el-table-column label="类型编号" align="center" prop="typeId" :formatter="typeFormatter" />
        <el-table-column label="系列编号" align="center" prop="seriesId" :formatter="seriesFormatter" />
        <el-table-column label="规格组" align="center" prop="specsMap" :formatter="specsFormatter" :show-overflow-tooltip="true" />
        <el-table-column label="成色组" align="center" prop="qualityIds" :formatter="qualityFormatter" :show-overflow-tooltip="true" />
        <el-table-column label="匹配情况" align="center" prop="hasMate">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.hasMate === 1">完全匹配</el-tag>
            <el-tag v-else-if="scope.row.hasMate === 2">已添加</el-tag>
            <el-tag type="warning" v-else>有缺损</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="品牌编号" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择品牌编号" filterable @change="brandIdChange">
            <el-option
              v-for="brand in brandList"
              :label="brand.brandName"
              :value="brand.brandId" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型编号" prop="typeId">
          <el-select v-model="form.typeId" filterable placeholder="请选择类型编号">
            <el-option
              v-for="type in goodsTypeOptions"
              :label="type.typeName"
              :value="type.typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="系列编号" prop="seriesId">
          <el-select v-model="form.seriesId" placeholder="请选择系列编号">
            <el-option
              v-for="series in seriesOptions"
              :label="series.seriesName"
              :value="series.seriesId" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格组" prop="specsMap">
          <el-cascader v-if="specsOptions.length > 0" v-model="form.specsMap" style="width: 100%"
            placeholder="选择商品规格组"
            :options="specsOptions"
            :props="{multiple: true}"
            filterable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="成色组" prop="qualityIds">
          <el-select multiple filterable v-model="form.qualityIds" placeholder="请选择成色组">
            <el-option
              v-for="quality in qualityList"
              :label="quality.qualityName"
              :value="quality.qualityId" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="goodsSort">
          <el-input v-model="form.goodsSort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShareGoods, getShareGoods, delGoods, addGoods, updateGoods, exportGoods } from "@/api/share/goods";
import {listBrand} from "@/api/share/brand"
import {listType} from "@/api/share/type"
import {listSeries} from "@/api/share/series"
import {listSpecs} from "@/api/share/specs"
import {listValues} from "@/api/share/values"
import {listQuality} from "@/api/share/quality"
import {arrayTranStr, strTranArray} from "@/utils/tran/shareUtils"
import XLSX from "xlsx";

export default {
  name: "Goods",
  components: {
  },
  data() {
    return {
      addFrom: {},
      addList: [],
      addOpen: false,
      //成色列表
      qualityList: [],
      // 规格列表
      specsOptions: [],
      // 系列选项
      seriesOptions: [],
      // 类型选项
      goodsTypeOptions: [],
      // 系列编号
      seriesList: [],
      //商品类型列表
      goodsTypeList: [],
      // 品牌列表
      brandList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        brandId: null,
        typeId: null,
        seriesId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌编号不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "类型编号不能为空", trigger: "change" }
        ],
        specsMap: [
          { required: true, message: "规格组不能为空", trigger: "change" }
        ],
        qualityIds: [
          { required: true, message: "成色组不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getBrandList();
    this.getGoodsTypeList();
    this.getSeriesList();
    this.getSpecsOptions();
    this.getQualityList();
  },
  methods: {
    /* 是否显示*/
    hasShowChange(row) {
      let title = row.hasShow === 1 ? '显示':'隐藏';
      this.$confirm("小程序是否" + title + "这条数据！", '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateGoods(row);
      }).then(resp => {
        this.msgSuccess("操作成功！")
        this.getList();
      }).finally(() => {
        this.getList();
      })
    },
    /*确认批量添加*/
    confirmAddList() {
      for (let i = 0; i < this.addList.length; i++) {
        addGoods(this.addList[i]).then(resp => {
          this.addList[i].hasMate = 2;
          this.msgSuccess("添加成功！");
        })
      }
      this.getList();
    },
    /*批量新增*/
    handleAddList() {
      this.addOpen = true;
      this.addList = [];
      this.addFrom = {
        brandId: null,
        typeId: null
      };
    },
    /*文件匹配*/
    changeFile(ev) {
      const _this = this;
      let f = ev.target.files[0];
      if(f == null) {
        return
      }
      let reader = new FileReader();
      reader.onload = function (e) {
        let data = e.target.result;
        let wb = XLSX.read(data, {type: "array"});
        let sheetNames = wb.SheetNames; //工作表名称合集
        let workSheet = wb.Sheets[sheetNames[0]]; //第一个
        let json = XLSX.utils.sheet_to_json(workSheet);
        _this.oldDataModelList(json);
      }
      reader.readAsArrayBuffer(f);
    },
    /*数据处理*/
    oldDataModelList(list) {
      let oneList = [];
      let modelName = "";
      for(let i = 0; i < list.length; i++) {
        if(list[i]['型号名称'] == null || list[i]['型号名称'] === '') {
          oneList.push(list[i]);
          continue
        }
        if(list[i]['型号名称'] !== modelName) {
          this.oneListFun(oneList);
          oneList = [];
          oneList.push(list[i]);
          modelName = list[i]['型号名称'];
        }
      }
      this.oneListFun(oneList);
    },
    /* 新增单条数据处理*/
    oneListFun(list) {
      if(list.length === 0){
        return
      }
      let modeName = list[0]['型号名称'];
      let color = list[0]['规格3'];
      let specs = "";
      for(let i = 0; i < list.length; i++) {
        specs += list[i]['规格1'] + ",";
      }
      let map = this.getSpecsMap(specs.substring(0, specs.length - 1), color);
      let specs2 = list[0]['规格2'];
      if(!(specs2 == null || specs2 === '')){
        map.specs.push([3,38])
      }
      let row = {
        goodsName: modeName,
        brandId: this.addFrom.brandId,
        typeId:this.addFrom.typeId,
        seriesId: 1,
        specsMap: JSON.stringify(map.specs),
        qualityIds: this.getQualityIds(list[0]),
        goodsSort: 1,
        hasMate: map.hasMate
      }
      this.addList.push(row);
    },
    getQualityIds(row) {
      let res = "";
      if(!(row['充新'] == null || row['充新'] === '')){
        res += 1 + ",";
      }
      if(!(row['靓机'] == null || row['靓机'] === '')){
        res += 2 + ",";
      }
      if(!(row['屏靓壳小磕'] == null || row['屏靓壳小磕'] === '')){
        res += 3 + ",";
      }
      if(!(row['屏细微壳小磕'] == null || row['屏细微壳小磕'] === '')){
        res += 4 + ",";
      }
      if(!(row['小花机'] == null || row['小花机'] === '')){
        res += 5 + ",";
      }
      if(!(row['花机'] == null || row['花机'] === '')){
        res += 6 + ",";
      }
      if(!(row['大花机'] == null || row['大花机'] === '')){
        res += 7 + ",";
      }
      if(!(row['外爆'] == null || row['外爆'] === '')){
        res += 8 + ",";
      }
      if(!(row['屏坏可测功能'] == null || row['屏坏可测功能'] === '')){
        res += 9 + ",";
      }
      return res.substring(0, res.length - 1);
    },
    /*获取规格组*/
    getSpecsMap(specs, color) {
      //全网通 [3,38];颜色 2;组合存储 7
      //先获取存储
      let specsRes = [];
      let hasMate = 1;
      let specsArr = specs.split(",");
      for(let i = 0; i < specsArr.length; i++) {
        specsArr[i] = specsArr[i].trim().replace(" ", "+");
        let res = this.specsStringTranId(specsArr[i], 7);
        if(res != null) {
          specsRes.push(res);
        }else {
          res = this.specsStringTranId(specsArr[i], 1);
          if(res == null) {
            hasMate = -1;
            console.log("未匹配到规格：" + specsArr[i]);
          }else {
            specsRes.push(res);
          }

        }
      }
      //获取颜色
      let colorArr = color.split("-");
      for(let j = 0; j < colorArr.length; j++) {
        let rs = this.specsStringTranId(colorArr[j], 2);
        if(rs != null) {
          specsRes.push(rs)
        }else {
          hasMate = -1;
          console.log("未匹配到颜色：" + colorArr[j]);
        }
      }
      // specsRes.push([3,38])
      let map = {
        specs: specsRes,
        hasMate: hasMate
      }
      return map;
    },
    //字符规格转换
    specsStringTranId(str, specsId){
      let res = null;
      for(let i = 0; i < this.specsOptions.length; i++) {
        if(this.specsOptions[i].value === specsId){
          for(let j = 0; j < this.specsOptions[i].children.length; j++) {
            if(str === this.specsOptions[i].children[j].label) {
              res = [specsId, this.specsOptions[i].children[j].value];
            }
          }
        }
      }
      return res;
    },
    /** 规格格式转换 */
    specsFormatter(row) {
      if(row.specsMap == null) {
        return null;
      }
      let res = "";
      let specsArr = JSON.parse(row.specsMap);
      for(let i = 0; i < specsArr.length; i++) {
        let str = "";
        for(let j = 0; j < this.specsOptions.length; j++) {
          if(specsArr[i][0] === this.specsOptions[j].value) {
            for(let c = 0; c < this.specsOptions[j].children.length; c++) {
              if(specsArr[i][1] === this.specsOptions[j].children[c].value) {
                str = "[" + this.specsOptions[j].label + "/" + this.specsOptions[j].children[c].label + "]";
                break;
              }
            }
          }
        }
        res += str + "_"
      }
      return res.substring(0, res.length - 1);
    },
    /** 成色格式转换 */
    qualityFormatter(row) {
      if(row.qualityIds == null) {
        return null;
      }
      let arr = strTranArray(row.qualityIds);
      let res = "";
      for(let i = 0; i < arr.length; i++) {
        for(let j = 0; j < this.qualityList.length; j++) {
          if(arr[i] === this.qualityList[j].qualityId) {
            res += this.qualityList[j].qualityName + "_";
            break;
          }
        }
      }
      return res.substring(0, res.length - 1);
    },
    /** 系列规格转换 */
    seriesFormatter(row) {
      for(let i = 0; i < this.seriesList.length; i++) {
        if(row.seriesId === this.seriesList[i].seriesId) {
          return this.seriesList[i].seriesName;
        }
      }
    },
    /** 类型规格转换 */
    typeFormatter(row) {
      for(let i = 0; i < this.goodsTypeList.length; i++) {
        if(row.typeId === this.goodsTypeList[i].typeId) {
          return this.goodsTypeList[i].typeName;
        }
      }
    },
    /** 品牌规格转换 */
    brandFormatter(row) {
      for(let i = 0; i < this.brandList.length; i++) {
        if(row.brandId === this.brandList[i].brandId) {
          return this.brandList[i].brandName;
        }
      }
    },
    /** 查询成色列表 */
    getQualityList() {
      listQuality({}).then(resp => {
        this.qualityList = resp.rows;
      })
    },
    /** 获取规格联级列表 */
    async getSpecsOptions() {
      this.specsOptions = [];
      let valuesArr;
      await listValues({}).then(res => {
        valuesArr = res.rows;
      })
      await listSpecs({}).then(resp => {
        for(let i = 0; i < resp.rows.length; i++) {
          let children = [];

          for(let j = 0; j < valuesArr.length; j++) {
            if(resp.rows[i].specsId === valuesArr[j].specsId) {
              let param = {label: valuesArr[j].valuesName, value: valuesArr[j].valuesId};
              children.push(param);
            }
          }

          let parent = {label: resp.rows[i].specsName, value: resp.rows[i].specsId, children: children};
          this.specsOptions.push(parent);
        }
      })
    },
    /** 品牌选择事件 */
    brandIdChange(e) {
      let brand;
      for(let i = 0; i < this.brandList.length; i++) {
        if(e === this.brandList[i].brandId) {
          brand = this.brandList[i];
        }
      }

      //获取品牌对应的系列列表
      listSeries({brandIds: e}).then(resp => {
        this.seriesOptions = resp.rows;
      })

      //获取品牌对应的类型列表
      let arr = brand.typesIds.split(",");
      this.goodsTypeOptions = [];
      for(let i = 0; i < arr.length; i++) {
        for(let j = 0; j < this.goodsTypeList.length; j++) {
          if(parseInt(arr[i]) === this.goodsTypeList[j].typeId) {
            this.goodsTypeOptions.push(this.goodsTypeList[j]);
            break;
          }
        }
      }
    },
    /** 系列列表 */
    getSeriesList() {
      listSeries({}).then(resp => {
        this.seriesList = resp.rows;
      })
    },
    /** 商品类型列表 */
    getGoodsTypeList() {
      listType({}).then(resp => {
        this.goodsTypeList = resp.rows;
      })
    },
    /** 品牌列表 */
    getBrandList() {
      listBrand({}).then(resp => {
        this.brandList = resp.rows;
      })
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listShareGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsName: null,
        brandId: null,
        typeId: null,
        seriesId: null,
        specsMap: null,
        qualityIds: [],
        goodsSort: null,
        hasShow: null
      };
      this.goodsTypeOptions = [];
      this.seriesOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids
      getShareGoods(goodsId).then(response => {
        this.form = response.data;
        this.form.qualityIds = strTranArray(this.form.qualityIds);
        this.form.specsMap = JSON.parse(this.form.specsMap);
        this.brandIdChange(this.form.brandId);
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.specsMap = JSON.stringify(this.form.specsMap);
          this.form.qualityIds = arrayTranStr(this.form.qualityIds);
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$confirm('是否确认删除商品信息编号为"' + goodsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(goodsIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportGoods(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
